"""
@file:  6.三乐购物系统
@author:  chenran
@date:   2020/06/21
@desc:
"""

# 1、使用系统需要登陆验证，进入系统后，输入预算信息
# 2、用户可以任意查看商品信息和已购信息
# 3、用户跟据商品编号购买信息，购买时检测余额是否充足，够就直接扣款，不够就提醒
# 4、可随时退出（输入exit），退出后，打印已购买商品和余额
# 5、将用户名密码余额存文件，下次进入系统可以直接用

# def goods_list():
#     pass


import json

# 登录
def login():
    username = input("请输入用户名：")
    passwd = input("请输入用户密码：")

    with open('users.txt', "r+", encoding = 'utf-8')as f:
        content = f.read()
        if content:
            users = json.loads(content)
        else:
            users = {}

    if username in users and passwd == users[username]['password']:
        print("欢迎光临三乐购物系统")
        money = users[username]['money']
        print(f"你的账户余额为{money}元")
        return username


# 注册
def register():
    username = input("请输入用户名：")

    with open('users.txt', 'r+', encoding = 'utf-8')as f:
        content = f.read()
        if content:
            users = json.loads(content)
        else:
            users = {}

        if username in users.keys():
            print("你已注册，请登录")
        else:
            password = input("请输入密码")
            users[username] = {'password':password ,'money':0}
            f.seek(0, 0)
            f.write(json.dumps(users))
            print("注册成功,充值后开始购物")

            recharge(username)


# 充值
def recharge(username):
    while True:
        user_money = input("请输入充值金额：")
        if user_money.isdigit():
            user_money = int(user_money )
            break
        else:
            print("请输入正确的数字")

    with open('users.txt', "r+", encoding='utf-8')as f:
        content = f.read()
        users = json.loads(content)
        a = users[username]['money'] + user_money
        users[username]['money'] = a

        f.seek(0, 0)
        f.write(json.dumps(users))
        print(f"充值成功，你的账户余额为：{a}元")

# 商品信息
def goods():
    with open('goods.txt',"r+", encoding = 'utf-8')as f:
        goods = json.loads(f.read())
        for key, value in goods.items():
            name = value['name']
            price = value['price']
            print(f'{key}\t{name}\t{price}')

# 扣款
def pay(choice, num, username):
    with open('goods.txt', 'r+', encoding = 'utf-8')as f:
        price = json.loads(f.read())[choice]['price']
        total = price*num

    with open ('users.txt', "r+", encoding = 'utf-8')as f:
        user = json.loads(f.read())
        money = user[username]['money']
        if money >= total:
            user[username]['money'] = money - total

            f.seek(0, 0)
            f.write(json.dump(choice, num))
        else:
            a = input('余额不足，请充值。充值请按1，输入exit退出')
            if a == '1':
                recharge(username)
            else:
                clearing()

#清算退出
def clearing():
    cart_list()
    with open ("cart.txt", "r+", encoding = 'utf-8')as f:
        print("欢迎下次光临")
        exit()

# 查看购物车
def cart_list():
    with open('cart.txt', 'r+', encoding='utf-8')as f:
        content = f.read()
        if content:
            cart = json.loads(content)
            price1 = 0
            for key, value in cart.items():
                num = value['num']
                price  = value['total']
                price1 += price
                print(f'{key}\t{num}\t{price}')
            print(f"你消费了{price1}元")
            with open('users.txt', 'r+', encoding='utf-8')as f:
                user = json.loads(f.read())
                a = user[username]['moeny']
                print(f"你的余额为{a}元")



# 登录注册页面，主程序
while True:
    choose = input("请输入你的选择："
                   "\n1：登录 "
                   "\n2：注册 "
                   "\nexit：退出")

    if choose == "1":
        username = login()
        break
    elif choose == "2":
        register()
    elif choose == "exit":
        print("你已退出")
    else:
        print("输入有误")


# 充值购物主程序
while True:
    goods()
    choice = input("请输入你要购买的商品代码,退出输入exit：")
    with open ('goods.txt', 'r+', encoding = 'utf-8')as f:
        content = f.read()
        choices = json.loads(content).keys()
        if choice in choices:
            while True:
                num = input("请输入购买数量：")
                if num.isdigit():
                    num = int(num)
                    break
                else:
                    print("请输入合法数字")
            pay(choice ,num, username)
            cart_list()
        elif choice == 'exit':
            clearing()
        else:
            print("输入有误")


